package cool.taomu.toolkit.demo.stock.service

import com.google.common.eventbus.EventBus
import com.google.inject.Inject
import org.jooq.DSLContext
import cool.taomu.toolkit.stock.dao.jooq.tables.TaomuStockHistory
import java.time.LocalDateTime
import java.time.temporal.ChronoUnit
import cool.taomu.toolkit.demo.stock.entity.StockHistory
import cool.taomu.toolkit.demo.stock.listener.entity.StockDataEvent

class DeviationService {
	@Inject
	EventBus bus

	@Inject
	DSLContext dsl;

	def deviationEvel(Integer xDays, String code) {
		var ncode = code
		if (code.startsWith("60")) {
			ncode = "sh." + code;
		} else if (code.startsWith("00")) {
			ncode = "sz." + code;
		}

		val endDate = LocalDateTime.now().toLocalDate().atStartOfDay();
		val startDate = endDate.minus(xDays, ChronoUnit.DAYS).toLocalDate().atStartOfDay();
		var stockHistorylist = dsl.selectFrom(TaomuStockHistory.TAOMU_STOCK_HISTORY).where(
			TaomuStockHistory.TAOMU_STOCK_HISTORY.CODE.eq(ncode)).and(
			TaomuStockHistory.TAOMU_STOCK_HISTORY.DATE.greaterOrEqual(startDate)
		).and(TaomuStockHistory.TAOMU_STOCK_HISTORY.DATE.lessOrEqual(endDate)).orderBy(
			TaomuStockHistory.TAOMU_STOCK_HISTORY.DATE.asc()).fetchInto(StockHistory)
		println(stockHistorylist.size)
		bus.post(new StockDataEvent(code, stockHistorylist))
	}

}
